import React from 'react';
import { Form, Divider, Button, Row, Col, Input, message, Modal, Spin } from 'antd';
import { history } from 'umi'

import { UploadOssCompact } from '@/containers';
import { useRequest, defaultFormatResult } from '@/hooks';

import { getThirdPartyInfo, updateThirdPartyInfo } from '@/pages/Recruitment/Hire/service';
import { primaryColor } from '@/defaultSettings';
import { TitleControl } from '@/pages/Recruitment/components';
import { SEX } from '@/pages/Recruitment/dictionary';
import { getDisplayText } from '@/utils/dataDictUtil';
import Pre from '@/components/Pre';

import { PageWrap } from './components';

const { TextArea } = Input;

const styleTitle = title => (
    <div style={{ fontWeight: 'bold', fontSize: 14, marginLeft: -7 }}>
        <Divider type="vertical" style={{ width: 4, background: primaryColor }} /> {title}
    </div>
);

const titleProps = {
    titleRender: styleTitle,
    showButton: false
};

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 }
};

const oneLineLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 19 }
};

const formItemLayoutExtra = {
    layout: 'vertical',
    wrapperCol: { span: 18 }
};

const renderItem = (EditComponent, ViewComponent, editFlag = true) => (editFlag ? EditComponent : ViewComponent);

const ThirdParty = ({ location, form }) => {
    const { query } = location;
    const { signBackgroundId } = query;

    // 候选人信息
    const { loading, data: info = {} } = useRequest(() => getThirdPartyInfo(signBackgroundId), {
        refreshDeps: [signBackgroundId],
        ...defaultFormatResult
    });

    // 保存候选人信息
    const { loading: submitLoading, run: runSubmit } = useRequest(updateThirdPartyInfo, {
        manual: true,
        ...defaultFormatResult
    });

    const isEdit = !info?.recruitTalentBackground?.evaluateRemark;
    // const isEdit = true;

    const handleSubmit = () => {
        const callSubmit = async values => {
            Modal.confirm({
                title: '确定要提交吗',
                // content: '提交后无法二次修改',
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                    const postParams = {
                        ...values,
                        backgroundId: info.backgroundId
                    };
                    const result = await runSubmit(postParams);
                    if (result) {
                        message.success('提交成功');
                        setTimeout(() => {
                            history.go(0);
                        }, 2000);
                    }
                },
                onCancel() {
                    console.log('Cancel');
                }
            });
        };

        form.validateFieldsAndScroll((errors, values) => {
            if (errors) return;
            callSubmit(values);
        });
    };

    const { getFieldDecorator } = form;

    const bannerText = (
        <>
            <div>感谢您的背调协作</div>
            <div>
                <strong>请反馈背调结果</strong>
            </div>
        </>
    );

    const getFileList = () => {
        const file = info?.recruitTalentBackgroundSalary?.talentOriginalFileUrl;
        if (file) {
            // 要不要考虑区分显示文件名与下载文件名
            const suffix = file.match(/\.(\w+)\??[^.]*$/)?.[1];
            return JSON.stringify([
                {
                    uid: 1,
                    url: file,
                    name: `${info?.recruitTalentBackgroundSalary?.talentName}的简历.${suffix}`
                }
            ]);
        }
        return '';
    };

    const fileList = getFileList();

    React.useEffect(() => {
        const existFile = info?.recruitTalentBackground?.uploadFileUrl;
        if (existFile) {
            form.setFieldsValue({
                uploadFileUrl: existFile
            });
        }
    }, [info]);

    return (
        <PageWrap bannerText={bannerText}>
            <Spin spinning={loading}>
                <Form {...formItemLayout}>
                    <TitleControl title="背调对象" {...titleProps}>
                        <Row>
                            <Col span={24}>
                                <Form.Item label="对象姓名" {...oneLineLayout}>
                                    {info?.recruitTalentBackgroundSalary?.talentName}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item label="性别/年龄" {...oneLineLayout}>
                                    {getDisplayText(SEX, info?.recruitTalentBackgroundSalary?.talentSex)}/
                                    {info?.recruitTalentBackgroundSalary?.talentAge}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item label="手机号" {...oneLineLayout}>
                                    {info?.recruitTalentBackgroundSalary?.talentPhone}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item label="邮箱" {...oneLineLayout}>
                                    {info?.recruitTalentBackgroundSalary?.talentEmail}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item label="简历" {...oneLineLayout}>
                                    {fileList && <UploadOssCompact value={fileList} editable={false} />}
                                </Form.Item>
                            </Col>
                        </Row>
                    </TitleControl>
                </Form>
                <Form {...(isEdit ? formItemLayoutExtra : formItemLayout)}>
                    <TitleControl title="背调结论" {...titleProps}>
                        <Row>
                            <Col span={24}>
                                <Form.Item
                                    label="背调结论"
                                    {...(isEdit ? { extra: '不超过200个字符' } : {})}
                                    {...(isEdit ? {} : oneLineLayout)}
                                >
                                    {renderItem(
                                        getFieldDecorator('evaluateRemark', {
                                            initialValue: info?.recruitTalentBackground?.evaluateRemark,
                                            rules: [{ required: true, message: '背调结论不能空' }]
                                        })(<TextArea maxLength={200} placeholder="请输入" style={{ height: 100 }} />),
                                        <Pre>{info?.recruitTalentBackground?.evaluateRemark}</Pre>,
                                        isEdit
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item
                                    required
                                    label="背调报告"
                                    extra={
                                        isEdit
                                            ? '支持 pdf、doc、docx、jpg、jpeg、rar 等格式的附件，单个文件大小为10MB以内'
                                            : ''
                                    }
                                    {...(isEdit ? {} : oneLineLayout)}
                                >
                                    {getFieldDecorator('uploadFileUrl', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '背调报告不能为空'
                                            }
                                        ]
                                    })(
                                        <UploadOssCompact
                                            rules={[
                                                { max: 10 },
                                                { type: ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'rar'] }
                                            ]}
                                            editable={isEdit}
                                        />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                    </TitleControl>
                </Form>
                {isEdit && (
                    <Row type="flex" justify="center">
                        <Button
                            type="primary"
                            style={{ margin: '0 auto' }}
                            onClick={handleSubmit}
                            loading={submitLoading}
                        >
                            提交
                        </Button>
                    </Row>
                )}
            </Spin>
        </PageWrap>
    );
};

export default Form.create()(ThirdParty);
